package com.tanhua.server.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.ContactVo;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.MessagesService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class MessagesServiceImpl implements MessagesService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 根据环信ID查询用户详细信息
     */
    @Override
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1.首先根据huanxinId查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2.根据用户id查询用户id
        //2.1从线程中取Long userId = UserThreadLocal.getUserId();
        //2.1从user中getId
        Long userId = user.getId();
        UserInfo info = userInfoApi.findById(userId);
        //3.创建返回对象vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(info, vo); //copy同名同类型的属性
        //4.类型不一样需要toString'操作一下
        if (info.getAge() != null) {
            vo.setAge(info.getAge().toString());
        }
        return vo;
    }

    /**
     * 添加好友:把friendID和userId加入到friend表当中
     *
     * @param friendId
     */
    @Override
    public void addFriend(Long friendId) {
        //1.获取当前用户id
        Long userId = UserThreadLocal.getUserId();
        //2.将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact("hx" + userId, "hx" + friendId);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.成功,调用api添加到MongoDB
        friendApi.addFriend(userId, friendId);
    }

    /**
     * 查询好友列表:传入分页数据 可能还有昵称参数
     */
    @Override
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1.调用Api查询当前用户的好友
        Long userId = UserThreadLocal.getUserId();
        //根据用户id查朋友关系表得到用户朋友的id
        List<Friend> list = friendApi.findByUserId(userId, page, pagesize);
        //判断是否存在好友
        if (CollUtil.isEmpty(list)) {
            //不存在,返回空
            return new PageResult();
        }
        //2.提取数据列表当中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);

        //通过好友id查询UserInfo得到每个好有的详情:可能有条件是昵称
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, userInfo);
        /*//封装数据返回:
        //1.创建一个集合接受数据
        ArrayList<ContactVo> list1 = new ArrayList<>();
        //2.遍历好友集合取出好友id
        for (Friend friend : list) {
            //3.键值对取出对象信息
            UserInfo fuserInfo = map.get(friend.getFriendId());
            if (fuserInfo!=null){
                ContactVo init = ContactVo.init(fuserInfo);
                list1.add(init);
            }
        }*/

        //stream流封装数据
        List<ContactVo> collect = list.parallelStream().filter(friend ->
                //过滤掉为null的
                map.get(friend.getFriendId()) != null)
                .map(friend ->
                        ContactVo.init(map.get(friend.getFriendId())))
                .collect(Collectors.toList());

        return new PageResult(page, pagesize, 0l, collect);
    }
}
